package com.iven.xie.code.generator.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.iven.xie.code.generator.bean.PageList;
import com.iven.xie.code.generator.bean.QueryBean;
import com.iven.xie.code.generator.dao.GeneratorDao;
import com.iven.xie.code.generator.service.CodeGeneratorService;
import com.iven.xie.code.generator.util.GeneratorUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author iven.xie
 */
@Service
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

    @Autowired
    private GeneratorDao generatorDao;

    @Override
    public PageList queryList(QueryBean queryBean) {
        Page<?> page = PageHelper.startPage(queryBean.getPage(), queryBean.getLimit());
        List<Map<String, Object>> list = generatorDao.queryList(queryBean);
        int total = (int) page.getTotal();
        return new PageList(list, total, queryBean.getLimit(), queryBean.getPage());
    }

    @Override
    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

    @Override
    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GeneratorUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
